package com.tqz.rc.server.healthcheck;

import java.util.Map;
import java.util.concurrent.*;

import static com.tqz.rc.common.constant.DefaultValueConstant.*;

/**
 * <p>检查检查处理器。
 *
 * @author tianqingzhao
 * @since 2021/8/31 14:50
 */
public class HealthCheckReactor {

    private static final Map<String, ScheduledFuture> futureMap = new ConcurrentHashMap<>();

    private static final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10);

    /**
     * 服务端初始化的时候，自己启动该任务进行心跳健康检查，延时5秒执行，每5秒钟执行一次。
     *
     * @param task 任务
     */
    public static void scheduleCheck(BeatCheckTask task) {
        futureMap.computeIfAbsent(task.taskKey(),
                key -> executorService.scheduleWithFixedDelay(task, SERVER_PROCESS_CLIENT_BEAT_CHECK_TASKINITIAL_DELAY_TIME,
                        SERVER_PROCESS_CLIENT_BEAT_CHECK_TASK_DELAY_TIME, TimeUnit.MILLISECONDS));
    }

    /**
     * 服务端接收客户端的请求进行健康检查，该任务为立马执行。
     *
     * @param task 任务
     * @return
     */
    public static ScheduledFuture<?> scheduleNow(Runnable task) {
        return executorService.schedule(task, CLIENT_BEAT_PROCESSOR_DELAY_TIME, TimeUnit.MILLISECONDS);
    }
}
